/*
========================================================================
 Name        : ExpensesListBoxView.cpp
 Author      : Vishal Dharankar
 Copyright   : Created by Vishal Dharankar 
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <akncontext.h>
#include <akntitle.h>
#include <eikbtgpc.h>
#include <Expenses.rsg>
// ]]] end generated region [Generated System Includes]
#include <eiktxlbm.h> 
#include <BADESCA.H>
#include "ExpensesListBox.h"
#include "expense.h"
#include "expensesAppUi.h"
#include "expenseslistbox.h"
// [[[ begin generated region: do not modify [Generated User Includes]

#include "Expenses.hrh"
#include "ExpensesListBoxView.h"
#include "ExpensesListBox.hrh"
#include "ExpensesForm.hrh"
// ]]] end generated region [Generated User Includes]
#include <W32STD.H> 
#include <EIKENV.H>
#include <s32file.h>
#include <e32const.h> 
#include "nameddatabase.h"
// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]
_LIT(KPath,"c:\\data\\expenses");
/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CExpensesListBoxView::CExpensesListBoxView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	iExpensesListBox = NULL;
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CExpensesListBoxView::~CExpensesListBoxView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	delete iExpensesListBox;
	iExpensesListBox = NULL;
	// ]]] end generated region [Generated Contents]
	
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CExpensesListBoxView
 */
CExpensesListBoxView* CExpensesListBoxView::NewL()
	{
	CExpensesListBoxView* self = CExpensesListBoxView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CExpensesListBoxView
 */
CExpensesListBoxView* CExpensesListBoxView::NewLC()
	{
	CExpensesListBoxView* self = new ( ELeave ) CExpensesListBoxView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}


/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CExpensesListBoxView::ConstructL()
	{
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_EXPENSES_LIST_BOX_EXPENSES_LIST_BOX_VIEW );
				
	// ]]] end generated region [Generated Code]
	
	// add your own initialization code here
	
	}

/**
 * @return The UID for this view
 */
TUid CExpensesListBoxView::Id() const
	{
	return TUid::Uid( EExpensesListBoxViewId );
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CExpensesListBoxView::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
	
		case EAknSoftkeyExit:
			commandHandled = HandleControlPaneRightSoftKeyPressedL( aCommand );
			break;
		case EExpensesListBoxViewTestMenuItemCommand:
			commandHandled = HandleTestMenuItemSelectedL( aCommand );
			break;
		case EExpensesListBoxViewAdd_ExpenseMenuItemCommand:
			commandHandled = HandleAdd_ExpenseMenuItemSelectedL( aCommand );
			break;
		case EExpensesListBoxViewView_MenuItemCommand:
			commandHandled = HandleView_MenuItemSelectedL( aCommand );
			break;
		case EExpensesListBoxViewDeleteMenuItemCommand:
			commandHandled = HandleDeleteMenuItemSelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		if ( aCommand == EAknSoftkeyExit )
			{
			AppUi()->HandleCommandL( EEikCmdExit );
			}
	
		}
	// ]]] end generated region [Generated Code]
	
	}

/**
 *	Handles user actions during activation of the view, 
 *	such as initializing the content.
 */
void CExpensesListBoxView::DoActivateL( 
		const TVwsViewId& /*aPrevViewId*/,
		TUid /*aCustomMessageId*/,
		const TDesC8& /*aCustomMessage*/ )
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
				
	if ( iExpensesListBox == NULL )
		{
		iExpensesListBox = CreateContainerL();
		iExpensesListBox->SetMopParent( this );
		AppUi()->AddToStackL( *this, iExpensesListBox );
		} 
	HandleExpensesListBoxViewActivatedL();
	// ]]] end generated region [Generated Contents]
	
	}

/**
 */
void CExpensesListBoxView::DoDeactivate()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	if ( iExpensesListBox != NULL )
		{
		AppUi()->RemoveFromViewStack( *this, iExpensesListBox );
		delete iExpensesListBox;
		iExpensesListBox = NULL;
		}
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * Handle status pane size change for this view (override)
 */
void CExpensesListBoxView::HandleStatusPaneSizeChange()
	{
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TVwsViewId view;
	AppUi()->GetActiveViewId( view );
	if ( view.iViewUid == Id() )
		{
		TInt result;
		TRAP( result, SetupStatusPaneL() );
		}
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}

// [[[ begin generated function: do not modify
void CExpensesListBoxView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_EXPENSES_LIST_BOX_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}

// ]]] end generated function

// [[[ begin generated function: do not modify
void CExpensesListBoxView::CleanupStatusPane()
	{
	}

// ]]] end generated function

/**
 *	Creates the top-level container for the view.  You may modify this method's
 *	contents and the CExpensesListBox::NewL() signature as needed to initialize the
 *	container, but the signature for this method is fixed.
 *	@return new initialized instance of CExpensesListBox
 */
CExpensesListBox* CExpensesListBoxView::CreateContainerL()
	{
	return CExpensesListBox::NewL( ClientRect(), NULL, this );
	}

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CExpensesListBoxView::HandleTestMenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
	
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CExpensesListBoxView::HandleAdd_ExpenseMenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
	CExpensesAppUi* ui = (CExpensesAppUi*)AppUi();
	ui->SetAddOrView(true);
	AppUi()->ActivateLocalViewL(TUid::Uid(EExpensesFormViewId));
	return ETrue;
	}
				
/**
 *	Handle the activated event
 */
void CExpensesListBoxView::HandleExpensesListBoxViewActivatedL()
	{
	// TODO: implement activated event handler	
		CTextListBoxModel* model = this->iExpensesListBox->ListBox()->Model();
		CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
		TBuf<50> buf;
		CExpensesAppUi* ui = (CExpensesAppUi*)AppUi();
		RArray<Expense>& expArray = ui->ExpArray();
		
		//Expense exp;
		TReal exp;
		TTime date;
		TDateTime d;
		TBuf<50> strNote;
		TBuf<10> strExp;
		for(TInt i=0; i < expArray.Count(); i++)
			{
				exp = expArray[i].GetExp();
				date = expArray[i].GetTime();
				d = date.DateTime();
				strExp.Format(_L("%2.2f"),exp);
				strNote = _L("");
				expArray[i].GetNote(strNote);
				CExpensesListBox::CreateListBoxItemL(buf,strExp,strNote);
				itemArray->AppendL(buf);
				this->iExpensesListBox->ListBox()->HandleItemAdditionL();
			}
	}
void CExpensesListBoxView::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane) 
	{
	 if(aResourceId == R_EXPENSES_LIST_BOX_MENU_PANE1_MENU_PANE)
		 {
			 if(this->iExpensesListBox->ListBox()->Model()->ItemTextArray()->MdcaCount() == 0)
				 {
				 aMenuPane->SetItemDimmed(EExpensesListBoxViewView_MenuItemCommand,true);
				 aMenuPane->SetItemDimmed(EExpensesListBoxViewDeleteMenuItemCommand,true);
				 }
			 else
				 {
				 aMenuPane->SetItemDimmed(EExpensesListBoxViewView_MenuItemCommand,false);
				 aMenuPane->SetItemDimmed(EExpensesListBoxViewDeleteMenuItemCommand,false);
				 }
		 }
	}
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CExpensesListBoxView::HandleDeleteMenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
	CExpensesAppUi* ui = (CExpensesAppUi*)AppUi();
	RArray<Expense>& expArray = ui->ExpArray();
	
	TInt sel = this->iExpensesListBox->ListBox()->CurrentItemIndex();
	expArray.Remove(sel);
	
	// refresh items
	CTextListBoxModel* model = this->iExpensesListBox->ListBox()->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	TBuf<50> buf;
	
	// delete items
	itemArray->Reset();
	
	//Expense exp;
	TReal exp;
	TTime date;
	TDateTime d;
	TBuf<50> strNote;
	TBuf<10> strExp;
	for(TInt i=0; i < expArray.Count(); i++)
		{
			exp = expArray[i].GetExp();
			date = expArray[i].GetTime();
			d = date.DateTime();
			strExp.Format(_L("%2.2f"),exp);
			strNote = _L("");
			expArray[i].GetNote(strNote);
			CExpensesListBox::CreateListBoxItemL(buf,strExp,strNote);
			itemArray->AppendL(buf);
			this->iExpensesListBox->ListBox()->HandleItemAdditionL();
		}
	
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CExpensesListBoxView::HandleView_MenuItemSelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
	CExpensesAppUi* ui = (CExpensesAppUi*)AppUi();
	ui->SetAddOrView(false);
	RArray<Expense>& expArray = ui->ExpArray();
	
	TInt sel = this->iExpensesListBox->ListBox()->CurrentItemIndex();
	
	ui->SetSelIndex(sel);
	
	ui->ActivateLocalViewL(TUid::Uid(EExpensesFormViewId));
	
	
	
	return ETrue;
	}
				
/** 
 * Handle the rightSoftKeyPressed event.
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CExpensesListBoxView::HandleControlPaneRightSoftKeyPressedL( TInt aCommand )
	{
	// TODO: implement rightSoftKeyPressed event handler
	CMyDBClass *db;
	db = CMyDBClass::NewL();
	
	CExpensesAppUi* ui = (CExpensesAppUi*)AppUi();
	RArray<Expense>& exp = ui->ExpArray();
	TInt cat = 0;
	TReal32 expense = 0;
	TInt64 date = 0;
	TBuf<200> note;
	for(TInt i = 0; i < exp.Count(); i++)
		{
			cat = exp[i].GetCategory();
			expense = exp[i].GetExp();
			date = exp[i].GetTime().Int64();
			exp[i].GetNote(note);
			db->UpdateDatabaseL(note,cat,expense,date);
		}
	
	delete db;
	
	return EFalse;
	}
				
